package com.blb.demo;

//嵌套同步代码块，线程1持有锁A需要B，线程2持有锁B需要A
public class Demo1 {
    private static Object lockA = new Object();
    private static Object lockB = new Object();

    public static void main(String[] args) {
        new Thread(() -> {
            synchronized (lockA) {
                System.out.println(Thread.currentThread().getName() + "持有A，需要B");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lockB) {
                    System.out.println(Thread.currentThread().getName() + "执行结束");
                }
            }
        }).start();
        new Thread(() -> {
            synchronized (lockB) {
                System.out.println(Thread.currentThread().getName() + "持有A，需要B");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lockA) {
                    System.out.println(Thread.currentThread().getName() + "执行结束");
                }
            }
        }).start();
    }
} 
